/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.prod.mrp.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.redragon.framework.util.JsonDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.common.inv.input.service.InvInputHeadService;
import com.erp.common.inv.stock.service.InvStockService;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.material.dao.data.DataBox;
import com.erp.masterdata.material.dao.model.MdMaterial;
import com.erp.prod.mrp.dao.model.ProdMrpBillR;
import com.erp.prod.mrp.dao.model.ProdMrpLine;
import com.erp.prod.mrp.dao.model.ProdMrpLineCO;
import com.erp.prod.mrp.service.ProdMrpBillRService;
import com.erp.prod.mrp.service.ProdMrpLineService;

@Controller
@RequestMapping("/web/prodMrpLine")
public class ProdMrpLineWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ProdMrpLineWebController.class);
    
    //服务层注入
    @Autowired
    private ProdMrpLineService prodMrpLineService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    @Qualifier("invStockServiceCommon")
    private InvStockService invStockServiceCommon;
    @Autowired
    @Qualifier("invInputHeadServiceCommon")
    private InvInputHeadService invInputHeadServiceCommon;
    @Autowired
    private ProdMrpBillRService prodMrpPoaRService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getProdMrpLineList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-11-18 16:27:28
     * @author 
     * @param pages
     * @param prodMrpLineCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdMrpLineList")
    public String getProdMrpLineList(Pages pages, ProdMrpLineCO prodMrpLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        //物料属性
        Map bomPropertyMap = DataBox.getBomPropertyMap();
        
        //分页查询数据
        List<ProdMrpLine> prodMrpLineList = this.prodMrpLineService.getProdMrpLineListByMrpHeadCode(pages, prodMrpLineCO);
        
        //获取mrp已生成poa的关联数据
        List<ProdMrpBillR> prodMrpPoaRList = this.prodMrpPoaRService.getRelateByMrpHeadCode(prodMrpLineCO.getMrpHeadCode(), "POA");
        //获取mrp已生成wip的关联数据
        List<ProdMrpBillR> prodMrpWipRList = this.prodMrpPoaRService.getRelateByMrpHeadCode(prodMrpLineCO.getMrpHeadCode(), "WIP");
        
        for(ProdMrpLine prodMrpLine: prodMrpLineList) {
            prodMrpLine.setMaterialName(materialMap.get(prodMrpLine.getMaterialCode()).toString());
            //获取物料信息
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodMrpLine.getMaterialCode());
            prodMrpLine.setMaterialUnit(materialUnitMap.get(mdMaterial.getMaterialUnit()).toString());
            prodMrpLine.setMaterialStandard(mdMaterial.getStandard());
            //获取库存数量
            prodMrpLine.setStockQuantity(this.invStockServiceCommon.getMaterialStockNumber(prodMrpLine.getMaterialCode()));
            //获取预计接收数量
            prodMrpLine.setWillInputQuantity(this.invInputHeadServiceCommon.getInputQuantityForNotStock(prodMrpLine.getMaterialCode()));
            
            //判断mrp行是否存在采购计划，如果存在存入poa行编码
            for(ProdMrpBillR prodMrpPoaR: prodMrpPoaRList) {
                if(prodMrpPoaR.getMrpLineCode().equals(prodMrpLine.getMrpLineCode())) {
                    prodMrpLine.setPoaLineCode(prodMrpPoaR.getBillLineCode());
                    break;
                }
            }
            
            //判断mrp行是否存在生产任务，如果存在存入wip头编码
            for(ProdMrpBillR prodMrpPoaR: prodMrpWipRList) {
                if(prodMrpPoaR.getMrpLineCode().equals(prodMrpLine.getMrpLineCode())) {
                    prodMrpLine.setWipHeadCode(prodMrpPoaR.getBillHeadCode());
                    break;
                }
            }
        }
        
        //页面属性设置
        model.addAttribute("prodMrpLineList", prodMrpLineList);
        model.addAttribute("pages", pages);
        model.addAttribute("bomPropertyMap", bomPropertyMap);
        
        return "prodMrp/tab/prodMrpLineTab";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-11-18 16:27:28
     * @author 
     * @param prodMrpLine
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdMrpLine")
    public String getProdMrpLine(ProdMrpLine prodMrpLine, Model model) {
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        Map bomPropertyMap = DataBox.getBomPropertyMap();
        
        //查询要编辑的数据
        if(prodMrpLine!=null&&prodMrpLine.getMrpLineId()!=null) {
            prodMrpLine = this.prodMrpLineService.getDataObject(prodMrpLine.getMrpLineId());
            
            //获取物料信息
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodMrpLine.getMaterialCode());
            prodMrpLine.setMaterialName(materialMap.get(prodMrpLine.getMaterialCode()).toString());
            prodMrpLine.setMaterialUnit(materialUnitMap.get(mdMaterial.getMaterialUnit()).toString());
            prodMrpLine.setMaterialStandard(mdMaterial.getStandard());
        }
        
        //页面属性设置
        model.addAttribute("prodMrpLine", prodMrpLine);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("bomPropertyMap", bomPropertyMap);
        
        return "prodMrp/pop/addLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-11-18 16:27:28
     * @author 
     * @param prodMrpLine
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editProdMrpLine")
    @ResponseBody
    public String editProdMrpLine(@Valid ProdMrpLine prodMrpLine, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            /*
            //参数校验
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getProdMpsLine";
            }
            */
            
            //对当前编辑的对象初始化默认的字段
            if(prodMrpLine.getMrpLineId()==null) {
                prodMrpLine.setMrpLineCode(SnowFlake.getConcurrentId().toString());
            }
            
            //保存编辑的数据
            this.prodMrpLineService.insertOrUpdateDataObject(prodMrpLine);
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-11-18 16:27:28
     * @author 
     * @param prodMrpLine
     * @return String
     *
     */
    @RequestMapping("deleteProdMrpLine")
    @ResponseBody
    public String deleteProdMrpLine(ProdMrpLine prodMrpLine, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(prodMrpLine!=null&&prodMrpLine.getMrpLineId()!=null) {
                //删除数据
                this.prodMrpLineService.deleteDataObject(prodMrpLine);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 自动创建采购计划
     * @date 2020年11月19日
     * @author dongbin
     * @param billHeadCode
     * @param model
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("autoCreatePoa")
    @ResponseBody
    public String autoCreatePoa(String mrpHeadCode, String mrpLineId, Model model, RedirectAttributes attr) {
        //判断参数
        if(StringUtils.isNotBlank(mrpLineId)) {
            try {
                //调用自动创建方法
                return this.prodMrpLineService.autoCreatePoa(mrpHeadCode, mrpLineId);
            }catch(Exception e) {
                return JsonDataUtil.getExecuteJson(-1, "自动生成采购计划执行错误");
            }
        }else {
            return JsonDataUtil.getExecuteJson(-1, "参数传递错误");
        }
    }
    
    
    
    /**
     * 
     * @description 自动创建生产任务
     * @date 2020年11月19日
     * @author dongbin
     * @param billHeadCode
     * @param model
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("autoCreateWipTask")
    @ResponseBody
    public String autoCreateWipTask(String mrpHeadCode, String mrpLineId, Model model, RedirectAttributes attr) {
        //判断参数
        if(StringUtils.isNotBlank(mrpLineId)) {
            try {
                //调用自动创建方法
                return this.prodMrpLineService.autoCreateWipTask(mrpHeadCode, mrpLineId);
            }catch(Exception e) {
                return JsonDataUtil.getExecuteJson(-1, "自动生成生产任务执行错误");
            }
        }else {
            return JsonDataUtil.getExecuteJson(-1, "参数传递错误");
        }
    }
}
